<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel">
        取消
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" style="width: 50%;margin: 0 auto;">
        <a-form-item label="渠道来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
             <a-select placeholder="请输入渠道来源" :disabled="isNoCredit" v-decorator.trim="[ 'source', validatorRules.source]"  :dropdownMatchSelectWidth="false"
           showSearch optionFilterProp="children">
               <a-select-option v-for="(item,index) in sourceList" :key="index" :value="item.name" >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item  label="客户姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入客户姓名" v-decorator.trim="[ 'name', validatorRules.name]"/>
        </a-form-item>
        <a-form-item  label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入联系电话" :maxLength="11" v-decorator.trim="[ 'tel', validatorRules.tel]"/>
        </a-form-item>
        <a-form-item label="身份证号码" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-input placeholder="请输入身份证号码" :maxLength="18" v-decorator.trim="[ 'idNumber', validatorRules.idNumber]" />
        </a-form-item>
        <a-form-item label="联系地址" :labelCol="labelCol" :wrapperCol="wrapperCol" >
         <a-input placeholder="请输入地址" v-decorator.trim="[ 'address', validatorRules.address]" />
       </a-form-item>
        <!-- <a-form-item label="收益总和" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-input placeholder="请输入收益总和"  v-decorator.trim="[ 'profit', validatorRules.profit]"/>
        </a-form-item>
        -->
        <a-form-item label="信用等级" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select placeholder="请输入信用等级" v-decorator.trim="[ 'credit', validatorRules.credit]"  :dropdownMatchSelectWidth="false"
           showSearch optionFilterProp="children" @change="changeSelect" >
           <a-select-option  :value="item" v-for="(item,index) in credit_options" :key="index">{{ item }}</a-select-option>
          </a-select>
        </a-form-item> 
        <a-form-item label="收益总和" :labelCol="labelCol" :wrapperCol="wrapperCol" >
         <a-input placeholder="请输入收益总和" v-decorator.trim="[ 'profit', validatorRules.profit]" />
       </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="身份信息">
            <j-image-upload v-model="fileList"  v-decorator.trim="[ 'fileName', validatorRules.fileName]" bizPath="business" text="上传" isMultiple></j-image-upload>
        </a-form-item>
        <div>
        </div>
        
      </a-form>
      <div style="margin-bottom: 20px;">紧急联系人信息：</div>
      <j-editable-table
      id="deliveryModal"
        :ref="refKeys[0]"
        :loading="materialTable.loading"
        :columns="materialTable.columns"
        :dataSource="materialTable.dataSource"
        :maxHeight="300"
        :rowNumber="false"
        :rowSelection="true"
        :actionButton="true"
        :dragSort="true"
        >
      </j-editable-table>
    </a-spin>
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import Vue from 'vue'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import JSelectPosition from '@/components/jeecgbiz/JSelectPosition'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import {addCustom, editCustom, getCustomOne,getConfigSourceList} from '@/api/api'
  import JImageUpload from '../../../components/jeecg/JImageUpload'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { VALIDATE_NO_PASSED, getRefPromise, validateFormAndTables } from '@/utils/JEditableTableUtil'
  export default {
    name: "EngineerModal",
    mixins: [JEditableTableMixin],
    components: {
      JImageUpload,
      JSelectPosition,
      JImageUpload
    },
    data () {
      return {
        sourceList: [],
        title:"操作",
        visible: false,
        refKeys: ['materialDataTable', ],
        tableKeys:['materialDataTable', ],
        activeKey: 'materialDataTable',
        materialTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: '姓名', key: 'name', width: '7%', type: FormTypes.input, placeholder: '请输入${title}',
            validateRules: [{ required: true, message: '${title}不能为空' }]},
            { title: '电话号码', key: 'tel', width: '8%', type: FormTypes.inputNumber,placeholder: '请输入${title}',
            validateRules: [{ required: true , message: '请输入正确的${title}',pattern:/^1[3456789]\d{9}$/}]},
            { title: '职业', key: 'career', width: '10%', type: FormTypes.input,placeholder: '请输入${title}',
            validateRules: [{ required: true, message: '${title}不能为空' }]},
            { title: '关系', key: 'relationship', width: '8%', type: FormTypes.input,placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]},
              { title: '住址', key: 'address', width: '15%', type: FormTypes.input,placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]},
            { title: '身份证号码', key: 'idNumber', width: '15%', type: FormTypes.input,placeholder: '请输入${title}',
              validateRules: [{ required: false, message: '请输入正确的${title}',pattern:/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/ }]},
          ]
        },
        modalWidth:800,
        drawerWidth:700,
        credit_options : ["风险", "正常", "优秀", "极好","黑名单"],
        fileList:[],
        id:"", //保存工程id
        isReadOnly: false,
        disableSubmit:false,
        dateFormat:"YYYY-MM-DD",
        validatorRules:{
          source:{
            rules: [{
              required: true, message: '请输入渠道来源'
            }]
          },
          name:{
            rules: [
              {
              required: true, message: '请输入客户姓名'
            }
            ]
          },
          tel:{
            rules: [{
              required: true,type: 'number',message: '请输入正确格式的联系号码(11位)', trigger: 'blur',
               transform (value) {
                  var moneyg = /^\d+$|^\d*\.\d+$/g
                  if (!moneyg.test(value) ) {
                    return false
                  }else{
                    if(value.length<11){
                      return false
                    }
                    return Number(value)
                  }
                }
            }]
          },
          idNumber:{
            rules: [{
              required: true,type: 'string', message: '请输入正确身份证号码', trigger: 'blur',
               transform (value) {
                  // var moneyg = /^\d+$|^\d*\.\d+$/g
                  var moneyg = /^\d+X?$/g
                  if (!moneyg.test(value) ) {
                    return false
                  }else{
                    if(value.length<18){
                      return false
                    }
                    return value
                  }
                }
            }]
          },
          address:{
            rules: [
              {
              required: true, message: '请输入地址'
            }
            ]
          },
          profit:{
            rules: [{
              required: true, message: '请输入收益总和', type: 'number', trigger: 'blur',
               transform (value) {
                  // var moneyg = /^\d+$|^\d*\.\d+$/g
                  // if (!moneyg.test(value) ) {
                  if (isNaN(value) || value === '' || value === null) {
                    return false
                  }else{
                    return Number(value)
                  }
                }
            }]
          },
          credit:{
            rules: [
              {
              required: true, message: '请输入信用等级'
            }
            ]
          },
          fileName:{
            rules: [
              {
              required: false, message: '请上传图片'
            }
            ]
          }
        },
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        wrapperCol1: {
          xs: { span: 24 },
          sm: { span: 7 },
        },
        uploadLoading:false,
        // confirmLoading: false,
        headers:{},
        // form:this.$form.createForm(this)
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token}
    },
    mounted () {
      this.getSourceList()
    },
    methods: {
      getSourceList(params) {
      let that = this;
      getConfigSourceList(params).then((res)=>{
        if(res) {
          that.sourceList = res.data.operatorList;
        }
      });
    },
      add () {
        this.materialTable.dataSource.splice(0,this.materialTable.dataSource.length)
        this.edit({});
      },
      edit (record) {
        let that = this;
        that.form.resetFields();
        that.id = record.id;
        that.visible = true;
        let params = {
          id : record.id
        }
        if(record.id == null){
          return
        }
    // 通过获取单个数据的接口(/custom/selectOne)
        getCustomOne(params).then(res => {
          // console.log(res.data,'getCustomOne');
          that.model = Object.assign({}, res.data);
          // <!-- 字段：客户姓名，联系电话，身份证号，地址，收益总和，信用等级 -->
          that.form.setFieldsValue(pick(that.model,'name','tel','idNumber','address','profit','credit','fileName','id','source'))
          // if(res.data.itemList){
            that.materialTable.dataSource.splice(0,that.materialTable.dataSource.length)
            that.materialTable.dataSource.push(...res.data.itemList)
            console.log(that.materialTable.dataSource,'that.materialTable.columns');
          // }
        })
      },
      close() {
        this.$emit('close');
        this.id = ''
        this.model = {};
        this.visible = false;
        this.disableSubmit = false;
      },
      loadData(){
        this.$emit('save');
      },
      classifyIntoFormData(allValues) {
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values
        if(this.model.id){
          billMain.id = this.model.id
        }
        return {
          info: JSON.stringify(billMain),
          rows: JSON.stringify(detailArr),
        }
      },
      handleOk() {
        const that = this;
        // 触发表单验证
        this.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormAndTables(this.form, tables)
      }).then(allValues => {
        if (typeof this.classifyIntoFormData !== 'function') {
          throw this.throwNotFunction('classifyIntoFormData')
        }
        let formData = this.classifyIntoFormData(allValues)
            that.confirmLoading = true;
            let obj;
            if(!this.model.id){
              formData.id = this.model.id;
              obj=addCustom(formData)
            console.log('add',formData);
            }else{
              obj=editCustom(formData);
            console.log('edit',formData);
            }
            obj.then((res)=>{
              if(res.code === 200){
                that.$emit('ok');
              }else{
                that.$message.warning(res.data.message);
              }
            }).finally(() => {
              that.loadData()
              that.confirmLoading = false;
              that.close();
            })
        // return this.request(formData)
      }).catch(e => {
        console.log(e,'err');
        if (e.error === VALIDATE_NO_PASSED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
        } else {
          console.error(e)
        }
      })
      
        // this.form.validateFields((err, values) => {
        //   if (!err) {
        //     that.confirmLoading = true;
        //     let formData = Object.assign(this.model,values);
        //     let obj;
        //     if(!this.model.id){
        //       formData.id = this.id;
        //       obj=addCustom(formData);
        //     }else{
        //       obj=editCustom(formData);
        //     }
        //     obj.then((res)=>{
        //       if(res.code === 200){
        //         that.$emit('ok');
        //       }else{
        //         that.$message.warning(res.data.message);
        //       }
        //     }).finally(() => {
        //       that.confirmLoading = false;
        //       that.close();
        //     })
        //   }
        // })
      },
      handleCancel() {
        this.materialTable.dataSource.splice(0,this.materialTable.dataSource.length)
        this.close()
      },

      validateName(rule, value, callback){
        let params = {
          name: value,
          id: this.model.id?this.model.id:0
        };
        checkEngineer(params).then((res)=>{
          if(res && res.code===200) {
            if(!res.data.status){
              callback();
            } else {
              callback("名称已经存在");
            }
          } else {
            callback(res.data);
          }
        });
      }
    }
  }
</script>

<style scoped>

</style>